/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.services.saving;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import src.domain.customer.Customer;
import src.domain.saving.Saving;
import src.services.CRUEDService;

/**
 *
 * @author jasuke
 */
public class SavingConverter implements Converter{
    
    public static List<Saving> savingDB;

    static {
       savingDB = new ArrayList<>(); 
       
       CRUEDService helper = new CRUEDService();
       List<Object[]> x = helper.findAllSQL(
               "select sav.savaccntId, sav.accountNo, sav.customer, sav.balance from Saving as sav order by sav.accountNo", null); 
              
       for(Object[] obj: x) {
           Saving sav = new Saving();
           sav.setSavaccntId((Integer) obj[0]);
           sav.setAccountNo((String) obj[1]);
           sav.setCustomer((Customer) obj[2]);
           sav.setBalance((BigDecimal) obj[3]);
           savingDB.add(sav);
       }
    }
        
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        if (submittedValue.trim().equals("")) {
            return null;
        } else {
            try {
                int number = Integer.parseInt(submittedValue);

                for (Saving p : savingDB) {
                    if (p.getSavaccntId() == number) {
                        return p;
                    }
                }

            } catch(NumberFormatException exception) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid saving"));
            }
        }

        return null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value == null || value.equals("")) {
            return "";
        } else {
            return String.valueOf(((Saving) value).getSavaccntId());
        }
    }
    
}
